#pragma once
#include <iostream>
#include <time.h>
#include <stdarg.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>

#define SIZE 1024

std::string defaultpath = "./log/";

enum
{
    Info = 0,
    Debug,
    Warning,
    Error,
    Fatal
};

enum
{
    Screen = 1,
    Onefile,
    Classfile
};

class Log
{
public:
    Log()
    {
        printMethod = Screen;
        path = defaultpath;
    }

    void changeMethod(int method)
    {
        printMethod = method;
    }

    std::string levelToString(int level)
    {
        switch (level)
        {
        case Info:
            return "Info";
        case Debug:
            return "Debug";
        case Warning:
            return "Warning";
        case Error:
            return "Error";
        case Fatal:
            return "Fatal";
        default:
            return "Log Error";
        }
    }

    void printLog(int level, const std::string &logtxt)
    {
        switch (printMethod)
        {
        case Screen:
            std::cout << logtxt << std::endl;
            break;
        case Onefile:
            printOnefile(logtxt);
            break;
        case Classfile:
            printClassfile(level, logtxt);
            break;
        default:
            break;
        }
    }
    void print(const std::string &logname, const std::string &logtxt)
    {
        int fd = open(logname.c_str(), O_WRONLY | O_CREAT | O_APPEND, 0666);
        if (fd < 0)
        {
            return;
        }
        write(fd, logtxt.c_str(), logtxt.size());
        close(fd);
    }

    void printOnefile(const std::string &logtxt)
    {
        std::string logname = path + "Log";
        print(logname, logtxt);
    }

    void printClassfile(const int &level, const std::string &logtxt)
    {
        std::string logname = "Log." + levelToString(level);
        print(logname, logtxt);
    }

    void operator()(int level, const char *format, ...)
    {
        time_t t = time(nullptr);
        struct tm *ctime = localtime(&t);
        char leftbuffer[SIZE];
        snprintf(leftbuffer, sizeof(leftbuffer), "[%s][%d-%d-%d %d:%d:%d]", levelToString(level).c_str(), ctime->tm_year,
                 ctime->tm_mon + 1, ctime->tm_mday, ctime->tm_hour, ctime->tm_min, ctime->tm_sec);

        va_list s;
        va_start(s, format);
        char rightbuffer[SIZE];
        vsnprintf(rightbuffer, sizeof(rightbuffer), format, s);
        va_end(s);

        char logtxt[2 * SIZE];
        snprintf(logtxt, sizeof(logtxt), "%s %s", leftbuffer, rightbuffer);
        printLog(level, logtxt);
    }

    ~Log()
    {
    }

private:
    int printMethod;
    std::string path;
};